<template>
  <div class="cart-container">
    <!-- 购物车标题 -->
    <h1 class="cart-title">我的购物车</h1>

    <!-- 购物车为空时的提示 -->
    <div v-if="goods.length === 0" class="empty-cart">
      🛒 您的购物车还是空的，快去添加商品吧！
    </div>

    <!-- 购物车列表（非空时显示） -->
    <div v-else class="cart-table-wrapper">
      <table class="cart-table">
        <thead>
          <tr>
            <!-- 全选复选框 -->
            <th class="table-checkbox">
              <input 
                type="checkbox" 
                v-model="isAllSelected" 
                @change="handleAllSelect"
                :disabled="goods.length === 0"
              >
            </th>
            <th class="table-id">编号</th>
            <th class="table-name">商品名</th>
            <th class="table-price">单价(元)</th>
            <th class="table-quantity">数量</th>
            <th class="table-subtotal">小计(元)</th>
            <th class="table-action">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="good in goods" :key="good.id" class="cart-item-row">
            <!-- 单个商品选中框 -->
            <td class="table-checkbox">
              <input 
                type="checkbox" 
                v-model="good.selected"
                @change="handleSingleSelect"
              >
            </td>
            <td class="table-id">{{ good.id }}</td>
            <td class="table-name">{{ good.name }}</td>
            <td class="table-price">{{ good.price.toFixed(2) }}</td>
            <!-- 数量修改控件 -->
            <td class="table-quantity">
              <button 
                class="quantity-btn minus-btn" 
                @click="handleQuantityChange(good, -1)"
                :disabled="good.quantity <= 1"
              >
                -
              </button>
              <input 
                type="number" 
                v-model.number="good.quantity" 
                class="quantity-input"
                min="1"
                @change="handleQuantityInput(good)"
              >
              <button 
                class="quantity-btn plus-btn" 
                @click="handleQuantityChange(good, 1)"
              >
                +
              </button>
            </td>
            <!-- 商品小计（单价*数量） -->
            <td class="table-subtotal">{{ (good.price * good.quantity).toFixed(2) }}</td>
            <!-- 删除商品 -->
            <td class="table-action">
              <button 
                class="delete-btn" 
                @click="handleDeleteGood(good.id)"
              >
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 购物车统计与操作区 -->
      <div class="cart-summary">
        <div class="summary-left">
          <button 
            class="delete-selected-btn" 
            @click="handleDeleteSelected"
            :disabled="selectedGoods.length === 0"
          >
            删除选中商品
          </button>
        </div>
        <div class="summary-right">
          <span class="summary-text">已选商品：<span class="summary-value">{{ totalCount }} 件</span></span>
          <span class="summary-text">选中商品总价：</span>
          <span class="summary-total-price">
            ¥{{ totalPrice.toFixed(2) }}
          </span>
          <button class="checkout-btn">去结算</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 1. 商品列表：新增 quantity（数量）字段，默认1件
const goods = ref([
  { id: 1, name: "苹果", price: 8, selected: false, quantity: 1 },
  { id: 2, name: "香蕉", price: 5, selected: false, quantity: 1 },
  { id: 3, name: "花生", price: 5, selected: false, quantity: 1 },
  { id: 4, name: "香蕉", price: 4, selected: false, quantity: 1 }
])

// 2. 计算属性：筛选选中的商品（复用性更高）
const selectedGoods = computed(() => {
  return goods.value.filter(good => good.selected)
})

// 3. 计算属性：选中商品总数（基于数量字段，而非商品个数）
const totalCount = computed(() => {
  return selectedGoods.value.reduce((total, good) => total + good.quantity, 0)
})

// 4. 计算属性：选中商品总价（基于数量*单价）
const totalPrice = computed(() => {
  return selectedGoods.value.reduce((total, good) => total + (good.price * good.quantity), 0)
})

// 5. 全选状态（双向关联）
const isAllSelected = computed({
  // 获取：判断所有商品是否都选中
  get() {
    return goods.value.length > 0 && selectedGoods.value.length === goods.value.length
  },
  // 设置：点击全选框时，同步所有商品的选中状态
  set(val) {
    goods.value.forEach(good => {
      good.selected = val
    })
  }
})

// 6. 事件：单个商品选中状态变化时，同步全选框状态
const handleSingleSelect = () => {
  // 无需额外逻辑，isAllSelected 的 get 会自动重新计算
}

// 7. 事件：全选框点击（兼容禁用状态）
const handleAllSelect = (e) => {
  isAllSelected.value = e.target.checked
}

// 8. 事件：修改商品数量（+1/-1）
const handleQuantityChange = (good, step) => {
  good.quantity += step
  // 确保数量不小于1（兜底）
  if (good.quantity < 1) good.quantity = 1
}

// 9. 事件：手动输入数量（处理非法值）
const handleQuantityInput = (good) => {
  // 输入为空或非数字时，重置为1
  if (isNaN(good.quantity) || good.quantity < 1) {
    good.quantity = 1
  }
}

// 10. 事件：删除单个商品
const handleDeleteGood = (id) => {
  if (confirm('确定要删除该商品吗？')) {
    goods.value = goods.value.filter(good => good.id !== id)
  }
}

// 11. 事件：删除选中商品
const handleDeleteSelected = () => {
  if (confirm(`确定要删除选中的 ${totalCount.value} 件商品吗？`)) {
    goods.value = goods.value.filter(good => !good.selected)
  }
}
</script>

<style scoped>
/* 全局容器样式 */
.cart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Microsoft YaHei", sans-serif;
}

/* 标题样式 */
.cart-title {
  color: #333;
  font-size: 24px;
  margin-bottom: 20px;
  border-bottom: 2px solid #f5f5f5;
  padding-bottom: 10px;
}

/* 空购物车样式 */
.empty-cart {
  text-align: center;
  padding: 80px 0;
  color: #666;
  font-size: 18px;
  background-color: #fafafa;
  border-radius: 8px;
}

/* 表格容器（避免溢出） */
.cart-table-wrapper {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 购物车表格样式 */
.cart-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;
}

/* 表格表头样式 */
.cart-table thead {
  background-color: #f5f5f5;
  color: #333;
}

.cart-table th,
.cart-table td {
  padding: 12px 15px;
  text-align: center;
  border-bottom: 1px solid #eee;
}

/* 表格列宽控制 */
.table-checkbox { width: 60px; }
.table-id { width: 80px; }
.table-name { width: 180px; text-align: left; }
.table-price { width: 120px; }
.table-quantity { width: 180px; }
.table-subtotal { width: 120px; }
.table-action { width: 100px; }

/* 商品行 hover 效果 */
.cart-item-row:hover {
  background-color: #fafafa;
}

/* 数量控件样式 */
.quantity-btn {
  width: 30px;
  height: 30px;
  border: 1px solid #eee;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.2s;
}

.quantity-btn:hover {
  background-color: #f5f5f5;
}

.quantity-btn:disabled {
  cursor: not-allowed;
  color: #ccc;
  background-color: #fafafa;
}

.quantity-input {
  width: 60px;
  height: 30px;
  text-align: center;
  border: 1px solid #eee;
  border-radius: 4px;
  margin: 0 5px;
  outline: none;
}

.quantity-input:focus {
  border-color: #409eff;
}

/* 按钮样式 */
.delete-btn {
  color: #f56c6c;
  border: none;
  background: transparent;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: all 0.2s;
}

.delete-btn:hover {
  background-color: #fff5f5;
}

.delete-selected-btn {
  color: #f56c6c;
  border: 1px solid #f56c6c;
  background-color: #fff;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.delete-selected-btn:hover {
  background-color: #fff5f5;
}

.delete-selected-btn:disabled {
  cursor: not-allowed;
  color: #ccc;
  border-color: #ccc;
  background-color: #fafafa;
}

.checkout-btn {
  background-color: #409eff;
  color: #fff;
  border: none;
  padding: 8px 24px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 20px;
  transition: all 0.2s;
}

.checkout-btn:hover {
  background-color: #3a8ee6;
}

/* 统计区样式 */
.cart-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-top: 1px solid #eee;
}

.summary-left {
  color: #666;
}

.summary-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.summary-text {
  color: #666;
  font-size: 14px;
}

.summary-value {
  color: #f56c6c;
  font-weight: 500;
}

.summary-total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: 700;
}

/* 响应式适配（小屏幕） */
@media (max-width: 768px) {
  .cart-container {
    padding: 10px;
  }

  /* 隐藏编号列 */
  .table-id {
    display: none;
  }

  .summary-right {
    flex-wrap: wrap;
    gap: 10px;
    justify-content: flex-end;
  }

  .checkout-btn {
    margin-left: 0;
    width: 100%;
  }
}
</style>